from PySide6.QtCore import QAbstractTableModel, Qt, QRect, QEvent
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QStyledItemDelegate, QWidget, QHBoxLayout, QPushButton, QApplication, QStyle, \
    QStyleOptionButton


class UserTableModel(QAbstractTableModel):
    def __init__(self, data=None):
        super().__init__()
        self._data = data or []  # 二维列表 [[行1], [行2], ...]
        self._headers = ["会员ID", "姓名", '联系方式', "注册日期", "当前余额", "最后消费", "总消费",
                         "消费次数", "余额状态","备注","操作"]
        self._keys = ["id", "name", "phone",
                      "registration_date", "current_balance", "last_consumption_date", "total_consumption",
                      "consumption_count", "balance_status", "description",'']

    def rowCount(self, parent=None):
        """获取行数"""
        return len(self._data)

    def columnCount(self, parent=None):
        """获取列数"""
        return len(self._headers)

    def data(self, index, role=Qt.DisplayRole):
        """检查data"""
        if not index.isValid():
            return None

        row = index.row()
        col = index.column()
        value = self._data[row].get(self._keys[col], "")

        if role == Qt.DisplayRole:
            # 特殊字段格式化
            if self._keys[col] == "last_consumption_date" and value:
                # 截取日期时间（去掉 T）
                value = value.strftime("%Y-%m-%d %H:%M:%S")
                return value
            elif col == len(self._keys):
                return '123'
            elif self._keys[col] == "last_consumption_date" and not value:
                return "—"
            elif isinstance(value, float) or isinstance(value, int):
                return str(value)
            else:
                return str(value)

        elif role == Qt.TextAlignmentRole:
            # 数字类字段右对齐
            if self._keys[col] in ["id", "phone", "current_balance", "total_consumption", "consumption_count"]:
                return Qt.AlignRight | Qt.AlignVCenter
            else:
                return Qt.AlignLeft | Qt.AlignVCenter

        elif role == Qt.BackgroundRole:
            # 隔行变色
            if row % 2 == 0:
                return QColor("#BCCDF1")

        return None

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        """
        设置表头，行头
        :param section: 表示“第几个”，从 0 开始
        :param orientation:Qt.Horizontal → 问的是列头（表格上方） Qt.Vertical → 问的是行头（表格左侧）
        :return:
        """
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return self._headers[section]
            else:
                return str(section + 1)
        return None

    def update_data(self, new_data):
        """刷新数据"""
        self.beginResetModel()
        self._data = new_data
        self.endResetModel()


class ConsumptionButtonDelegate(QStyledItemDelegate):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.consume_callback = None  # 回调函数：def callback(row: int)

    def paint(self, painter, option, index):
        # 只绘制按钮外观（不创建真实控件）
        if index.column() == 10:  # 替换为你的按钮列索引
            style_option = QStyleOptionButton()
            # 用按钮初始化样式选项（关键！）
            # 手动覆盖 rect 和 text（因为按钮未显示，布局未计算）
            style_option.rect = option.rect.adjusted(2, 2, -2, -2)
            style_option.text = "消费"
            # 使用当前应用样式绘制按钮
            style = QApplication.style()
            style.drawControl(QStyle.CE_PushButton, style_option, painter)
        else:
            super().paint(painter, option, index)

    def editorEvent(self, event, model, option, index):
        # 只处理目标列
        if index.column() != 10:
            return False
        # 检测鼠标左键释放（模拟按钮点击）
        if event.type() == QEvent.MouseButtonRelease and event.button() == Qt.LeftButton:
            row = index.row()
            if self.consume_callback:
                self.consume_callback(row)  # ✅ 传出行号！
            return True  # 事件已处理

        return False

    def createEditor(self, parent, option, index):
        # 禁止编辑：返回 None 表示该单元格不可编辑
        return None
